package com.charm.restaurant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.charm.restaurant.common.Result;
import com.charm.restaurant.entity.Inventory;
import com.charm.restaurant.entity.Purchase;
import com.charm.restaurant.mapper.PurchaseMapper;
import com.charm.restaurant.service.InventoryService;
import com.charm.restaurant.service.PurchaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 采购服务实现类
 */
@Slf4j
@Service
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, Purchase> implements PurchaseService {

    @Autowired
    private InventoryService inventoryService;

    /**
     * 新增采购单
     */
    @Override
    @Transactional
    public Result<Purchase> savePurchase(Purchase purchase) {
        // 设置采购单号、状态等信息
        purchase.setNumber(String.valueOf(System.currentTimeMillis()));
        purchase.setStatus(1); // 1表示待审核
        purchase.setPurchaseTime(LocalDateTime.now());
        
        this.save(purchase);
        return Result.success(purchase);
    }

    /**
     * 分页查询采购单
     */
    @Override
    public Result<Page<Purchase>> pagePurchase(int page, int pageSize, String name) {
        Page<Purchase> pageInfo = new Page<>(page, pageSize);
        
        LambdaQueryWrapper<Purchase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Purchase::getInventoryName, name);
        queryWrapper.orderByDesc(Purchase::getPurchaseTime);
        
        this.page(pageInfo, queryWrapper);
        
        return Result.success(pageInfo);
    }

    /**
     * 根据ID查询采购单
     */
    @Override
    public Result<Purchase> getPurchaseById(Long id) {
        Purchase purchase = this.getById(id);
        if (purchase == null) {
            return Result.error("采购单不存在");
        }
        return Result.success(purchase);
    }

    /**
     * 修改采购单
     */
    @Override
    @Transactional
    public Result<Purchase> updatePurchase(Purchase purchase) {
        // 检查采购单是否存在
        Purchase existPurchase = this.getById(purchase.getId());
        if (existPurchase == null) {
            return Result.error("采购单不存在");
        }
        
        // 只有状态为1（待审核）的采购单可以修改
        if (existPurchase.getStatus() != 1) {
            return Result.error("采购单状态不允许修改");
        }
        
        this.updateById(purchase);
        return Result.success(purchase);
    }

    /**
     * 删除采购单
     */
    @Override
    @Transactional
    public Result<String> deletePurchase(List<Long> ids) {
        // 检查采购单状态，只有待审核状态可以删除
        LambdaQueryWrapper<Purchase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Purchase::getId, ids);
        queryWrapper.ne(Purchase::getStatus, 1); // 不等于待审核状态
        
        long count = this.count(queryWrapper);
        if (count > 0) {
            return Result.error("只有待审核状态的采购单可以删除");
        }
        
        this.removeByIds(ids);
        return Result.success("删除采购单成功");
    }

    /**
     * 更新采购单状态
     */
    @Override
    @Transactional
    public Result<String> updateStatus(Long id, Integer status) {
        Purchase purchase = this.getById(id);
        if (purchase == null) {
            return Result.error("采购单不存在");
        }
        
        // 状态校验
        if (purchase.getStatus() == 3 || purchase.getStatus() == 4) {
            return Result.error("已完成或已取消的采购单不能更改状态");
        }
        
        purchase.setStatus(status);
        this.updateById(purchase);
        
        return Result.success("更新采购单状态成功");
    }

    /**
     * 入库处理（采购完成）
     */
    @Override
    @Transactional
    public Result<String> inStock(Long id) {
        Purchase purchase = this.getById(id);
        if (purchase == null) {
            return Result.error("采购单不存在");
        }
        
        // 只有状态为2（已审核）的采购单可以入库
        if (purchase.getStatus() != 2) {
            return Result.error("采购单状态不正确，无法入库");
        }
        
        // 查询是否存在该商品的库存
        LambdaQueryWrapper<Inventory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Inventory::getName, purchase.getInventoryName());
        
        // 假设使用InventoryService更新库存
        Inventory inventory = null;
        
        // 这里简化处理，实际可能需要根据具体业务逻辑调整
        Result<String> result = inventoryService.updateStock(purchase.getInventoryId(), purchase.getQuantity(), "in");
        if (!"1".equals(result.getCode())) {
            return result;
        }
        
        // 更新采购单状态为已完成
        purchase.setStatus(3); // 3表示已完成
        this.updateById(purchase);
        
        return Result.success("入库成功");
    }
} 